from fastapi import APIRouter
from pydantic import BaseModel, Field, validator
from datetime import date
from typing import List, Optional

order_router = APIRouter()


@order_router.get("/get")
async def get_order():
    return {
        "code": 200,
        "msg": "success",
        "data": {
            "order_id": 1,
            "order_name": "order_name",
            "order_price": 100,
            "order_status": "success",
            "order_user": "user_name",
            "order_product": "product_name",
        }
    }


class Address(BaseModel):
    province: str
    city: str


# 需要限定传入的参数类型
class User(BaseModel):
    # username: str = Field(pattern=r'^a\w+$')  # username必须是a开头
    username: str
    age: int = Field(default=18, gt=0, lt=120)  # 默认值为18，大于0，小于100
    birthday: Optional[date] = None  # date类型，可以为None，默认值为None
    friends: List[int]
    description: Optional[str] = None
    address: Optional[Address] = None

    @validator('username')
    @classmethod
    # 注意，@validator只能用在类方法上，所以必须添加注解@classmethod，同时传入方法的第一个参数必须是cls（指向这个类本身）
    def username_must_alpha(cls, value):
        assert value.isalpha(), "username must be alpha"
        return value


@order_router.post("/data")
async def data(user: User):
    print(user, type(user))
    print(user.username)
    print(user.dict())  # 将user以字典的形式输出
    return {
        "code": 200,
        "msg": "success",
        "data": user
    }
